package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.HotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements HotelService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 根据关键字搜索酒店信息
     *
     * @param params 请求参数对象，包含用户输入的关键字
     * @return 酒店文档列表
     */
    @Override
    public PageResult search(RequestParams params) {

        try {
            SearchRequest request = new SearchRequest("hotel");
            //条件过滤
            buildBasicQuery(params, request);
            //2.分页
            if (params.getPage() == null) {
                params.setPage(0);
            }
            if (params.getSize() == null) {
                params.setSize(10);
            }
            request.source().from((params.getPage() - 1) * params.getSize()).size(params.getSize());
            //3.排序规则
            if ("default".equals(params.getSortBy())) {
                request.source().sort("score", SortOrder.DESC);
            } else {
                request.source().sort(params.getSortBy(), SortOrder.DESC);
            }
            //地理位置排序
            if (StringUtils.isNoneEmpty(params.getLocation())) {
                request.source().sort(
                        SortBuilders.geoDistanceSort("location", new GeoPoint())
                                .order(SortOrder.DESC)
                                .unit(DistanceUnit.KILOMETERS));
            }

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            return parseResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 条件过滤
     *
     * @param params
     * @param request
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.添加关键字查询
        if (StringUtils.isNoneEmpty(params.getKey())) {
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        //过滤条件--city
        if (StringUtils.isNoneEmpty(params.getCity())) {
            boolQuery.must(QueryBuilders.termQuery("city", params.getCity()));
        }
        //过滤条件--brand
        if (StringUtils.isNoneEmpty(params.getBrand())) {
            boolQuery.must(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //过滤条件--starName
        if (StringUtils.isNoneEmpty(params.getStarName())) {
            boolQuery.must(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        //过滤条件--价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.must(QueryBuilders.rangeQuery("price")
                    .gte(params.getMaxPrice()).lte(params.getMinPrice()));
        }
        //算分控制
        FunctionScoreQueryBuilder isAD = QueryBuilders.functionScoreQuery(boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        QueryBuilders.termQuery("isAD", true),
                        ScoreFunctionBuilders.weightFactorFunction(100)
                )
        });
        request.source().query(isAD);


        request.source().query(boolQuery);
    }


    /**
     * 条件过滤查询桶的聚合
     *
     * @param params
     * @return Map
     * - key是字符串，城市、星级、品牌、价格
     * -value是集合，例如多个城市的名称
     */
//    @Override
//    public Map<String, List<String>> getFilters(RequestParams params) {
//        try {
//            SearchRequest request = new SearchRequest("hotel");
//            //聚合规则方法调用
//            request.source().size(0);
//            AggregationRules(request,"city_agg","city");
//            AggregationRules(request,"brand_agg","brand");
//            AggregationRules(request,"starName_agg","starName");
//            //发出请求
//            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//            //解析response中的bucket并封装为集合
//            Aggregations aggregations = response.getAggregations();
//
//            List<String> cityList = paresBucket(aggregations,"city_agg");
//            List<String> brandList = paresBucket(aggregations,"brand_agg");
//            List<String> starNameList = paresBucket(aggregations,"starName_agg");
//
//            Map<String,List<String>> map = new HashMap<>();
//            map.put("city",cityList);
//            map.put("brand",brandList);
//            map.put("starName",starNameList);
//
//            return map;
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        //返回HashMap避免空指针异常
//        return new HashMap<>();
//    }
//    //解析response中的bucket并封装为集合
//    private List<String> paresBucket(Aggregations aggregations, String aggName) {
//
//        return null;
//
//    }
//    //聚合规则方法
//    private void AggregationRules(SearchRequest request, String aggsName, String aggField) {
//        request.source().aggregation(AggregationBuilders.terms(aggsName).field(aggField).size(100));
//    }
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(params, request);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("品牌", brandList);
            // 4.2.根据品牌名称，获取品牌结果
            List<String> cityList = getAggByName(aggregations, "cityAgg");
            result.put("城市", cityList);
            // 4.3.根据品牌名称，获取品牌结果
            List<String> starList = getAggByName(aggregations, "starAgg");
            result.put("星级", starList);

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 聚合抽取方法
     *
     * @param request
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100)
        );
    }


    /**
     * //结果解析抽取方法
     *
     * @param aggregations
     * @param aggName
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }


    /**
     * 解析结果
     */
    private PageResult parseResponse(SearchResponse response) {
        PageResult result = new PageResult();
        //解析结果
        SearchHits searchHits = response.getHits();
        //查询总记录数
        long value = searchHits.getTotalHits().value;
        result.setTotal(value);
        //获取参数
        SearchHit[] hits = searchHits.getHits();

        //创建集合封装对象
        List<HotelDoc> list = new ArrayList<>(hits.length);
        //转化为JSON格式
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }

            // 获取高亮结果
            Map<String, HighlightField> map = hit.getHighlightFields();
            // 根据字段名获取高亮结果
            if (map != null && map.size() > 0) {
                HighlightField highlightField = map.get("name");
                if (highlightField != null) {
                    // 获取高亮值
                    String HighName = highlightField.getFragments()[0].toString();
                    // 覆盖非高亮结果
                    hotelDoc.setName(HighName);
                }
            }
            list.add(hotelDoc);
            result.setHotels(list);
        }
        return result;
    }


    /**
     * 自动补全
     *
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            //准备request
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)  //查询的关键字
                            .size(10)
                            .skipDuplicates(true)
            ));
            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //解析数据
            Suggest suggest = response.getSuggest();
            //根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //遍历...获取options的长度是为了避免list集合扩容
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>(0);
    }

    /**
     * 后台删除
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hotel", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改和新增--全量修改
     *
     * @param id
     */
    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询酒店数据
            Hotel hotel = getById(id);
            // 转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
